package com.lyf.boot.convert;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.idev.excel.converters.Converter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.ReadCellData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;
import com.lyf.boot.annotation.ExcelDictFormat;
import com.lyf.boot.core.service.IDictService;
import com.lyf.boot.utils.poi.ExcelUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Luyufan
 * @date 2023/8/15 9:13
 */
@Slf4j
public class ExcelDictConvert implements Converter<Object> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return Object.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;
    }

    @Override
    public Object convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        ExcelDictFormat anno = AnnotationUtil.getAnnotation(contentProperty.getField(), ExcelDictFormat.class);
        String type = anno.dictType();
        String value = cellData.getStringValue();
        if(StrUtil.isBlank(value)){
            return null;
        }
        String key;
        if(StrUtil.isBlank(type)){
            key = ExcelUtil.reverseByExp(value, anno.readConverterExp(), anno.separator());
        }else{
            key = SpringUtil.getBean(IDictService.class).getDictKey(type, value, anno.separator());
        }
        return Convert.convert(contentProperty.getField().getType(), key);
    }

    @Override
    public WriteCellData<String> convertToExcelData(Object object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if(ObjectUtil.isNull(object)){
            return new WriteCellData<>("");
        }
        ExcelDictFormat anno = AnnotationUtil.getAnnotation(contentProperty.getField(), ExcelDictFormat.class);
        String type = anno.dictType();
        String key = Convert.toStr(object);
        String value;
        if(StrUtil.isBlank(type)){
            value = ExcelUtil.convertByExp(key, anno.readConverterExp(), anno.separator());
        }else{
            value = SpringUtil.getBean(IDictService.class).getDictValue(type, key, anno.separator());
        }
        return new WriteCellData<>(value);
    }
}
